package core

import (
    //"fmt"
	"encoding/json"
	"io/ioutil"
	"net/http"
	"bytes"
)

type PostJSONClient struct {
	
}
// method: "GET/POST" 
func (c *PostJSONClient) Excute(method, serverUrl string, request interface{}, response interface{}) ([]byte, error) {
	var (
		req   *http.Request
		err   error
		body  []byte
	)
	if method == "GET" {
	    req, err = http.NewRequest(method, serverUrl, nil)
		if err != nil {
			return nil, err
		}
	} else {
		if request != nil {
		    body, err = json.Marshal(request)
		    if err != nil {
				return nil, err
			}
		}
		req, err = http.NewRequest(method, serverUrl, bytes.NewBuffer(body))
		if err != nil {
			return nil, err
		}
		req.Header.Set("Content-Type", "application/x-www-form-urlencoded") //必须
	}
	client := &http.Client{}
	return clientDo(client, req, response)
}

func clientDo(client *http.Client, req *http.Request, response interface{}) ([]byte, error) {
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	data, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	//fmt.Println(string(data))
	if response != nil {
		return data, json.Unmarshal(data, &response)
	}
	return data, nil
}

func GetPostJSONClient() *PostJSONClient {
	return &PostJSONClient{
	}
}
